<template>
	<div class="search">
		<!-- 导航栏 -->
		<van-nav-bar
			fixed
			left-arrow
			@click-left="$router.back()"
			@click-right="keyword = ''"
			:right-text="searchList.length ? `清空结果` : ''"
			safe-area-inset-top
			placeholder
		>
			<template #title>
				<van-search
					v-model.trim="keyword"
					placeholder="请输入搜索关键词"
					clear-trigger="focus"
					shape="round"
					autofocus
					@search="searchFn"
					@cancel="keyword = ''"
				/>
			</template>
		</van-nav-bar>

		<!-- 历史记录 -->
		<van-divider
			v-show="!searchList.length && historyList.length"
			content-position="left"
			:hairline="false"
			dashed
		>
			历史记录
		</van-divider>
		<div class="group" v-show="!searchList.length && historyList.length">
			<div class="list">
				<span
					class="item"
					v-for="(item, index) in historyList"
					:key="index"
					@click="searchFn(item)"
				>
					{{ item }}
				</span>
			</div>
		</div>

		<!-- 搜索结果 -->
		<van-divider content-position="left" :hairline="false" dashed>搜索结果</van-divider>
		<div class="result" v-show="searchList.length">
			<div
				class="item"
				@click="$router.push({ name: 'Article', query: { id: item.id } })"
				v-for="item in searchList"
				:key="item.id"
				:to="`/article/${item.id}`"
			>
				<span class="text">{{ item.title }}</span>
				<i class="iconfont iconjiantou1"></i>
			</div>
		</div>

		<!-- 空状态 -->
		<van-empty v-show="!searchList.length" description="空空如也" />
	</div>
</template>

<script>
import { searchAPI } from '../api/search.js';
import { setSearchHistory, getSearchHistory } from '../utils/localStorage.js';
export default {
	components: {},
	data() {
		return {
			keyword: '',
			searchList: [],
			historyList: getSearchHistory() ? getSearchHistory() : []
		};
	},
	methods: {
		// 搜索请求事件
		async searchFn(keyword) {
			// 安全阻断
			if (keyword) this.keyword = keyword;
			if (this.keyword === '') return this.$toast.fail('请输入搜索关键词');
			// 搜索列表
			const { data } = (await searchAPI({ keyword: this.keyword })).data;
			this.searchList = data;
			// 追加历史记录
			this.historyList.unshift(this.keyword);
			// 查重历史记录
			this.historyList = [...new Set(this.historyList)];
		}
	},
	watch: {
		keyword: {
			handler() {
				// 空关键词判断
				if (this.keyword === '') this.searchList = [];
			}
		},
		historyList: {
			handler() {
				// 限制搜索记录长度最大为10
				if (this.historyList.length >= 10) this.historyList.length = 10;
				setSearchHistory(this.historyList);
			}
		}
	}
};
</script>

<style lang="less" scoped>
.search {
}
.result {
	.item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		border-bottom: 1px solid #ccc;
	}
}
.group {
	margin-top: 10px;
	padding: 10px;
	.list {
		display: flex;
		flex-wrap: wrap;
		.item {
			padding: 5px;
			font-size: 13px;
			margin-right: 10px;
			border: 1px solid #ccc;
		}
	}
}
</style>
